package com.example.shirodemo.authentication;

import com.example.core.utils.RedisUtil;
import com.example.shirodemo.entities.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ShiroHelper extends JwtShiroRealm {
    @Autowired
    RedisUtil redisUtil;

    /**
     * 获取当前用户的角色和权限集合
     *
     * @return AuthorizationInfo
     */
    public AuthorizationInfo getCurrentUserAuthorizationInfo() {
        return super.doGetAuthorizationInfo(null);
    }

    /**
     * 获取当前登录的用户
     *
     * @return
     */
    public User getCurrentUser() {
        return (User) SecurityUtils.getSubject().getPrincipal();
    }


    /**
     * 删除用户权限缓存
     */
    public void clearCache() {
        redisUtil.hmRemove(RedisUtil.USER_REDIS_ROLES, String.valueOf(getCurrentUser().getId()));
        redisUtil.hmRemove(RedisUtil.USER_REDIS_PERMISSIONS, String.valueOf(getCurrentUser().getId()));
    }

    /**
     * 退出登录
     */
    public void logout() {
        redisUtil.hmRemove(RedisUtil.USER_REDIS_LOGIN, String.valueOf(getCurrentUser().getId()));
    }
}
